﻿namespace MicroCloud.Api.Authorization.Areas.Admin.Controllers.Auth
{
    #region "角色数据权限管理"
    /// <summary>
    /// 角色数据权限管理
    /// </summary>
    [Description("角色数据权限管理")]
    [ModuleInfo(Code = "RoleEntity", Name = "角色数据权限管理", OrderNo = 4, Position = "Auth", PositionName = "授权模块")]
    public class RoleEntityController : AdminControllerBase
    {
        #region "属性"
        #region "获取 数据权限管理器"
        /// <summary>
        /// 获取 数据权限管理器
        /// </summary>
        protected DataAuthManager DataAuthManager => ServiceProvider.GetService<DataAuthManager>();
        #endregion

        #endregion

        #region "Action方法"
        #region "读取角色数据权限"
        /// <summary>
        /// 读取角色数据权限
        /// </summary>
        /// <param name="request">页请求信息</param>
        /// <returns>角色数据权限列表分页信息</returns>
        [HttpPost]
        [ModuleInfo]
        [DependOnFunction("ReadNode", Controller = "Role")]
        [DependOnFunction(nameof(EntityInfoController.ReadProperties), Controller = nameof(EntityInfoController))]
        [Description("读取")]
        public virtual PageData<EntityRoleOutputDto> Read(PageRequest request)
        {
            Check.NotNull(request, nameof(request));
            IFunction function = this.GetExecuteFunction();

            Expression<Func<EntityRole, bool>> predicate = FilterService.GetExpression<EntityRole>(request.FilterGroup);
            request.AddDefaultSortCondition(new SortCondition("RoleId"), new SortCondition("EntityId"), new SortCondition("Operation"));
            //if (request.PageCondition.SortConditions.Length == 0)
            //{
            //    request.PageCondition.SortConditions = new[]
            //    {
            //        new SortCondition("RoleId"),
            //        new SortCondition("EntityId"),
            //        new SortCondition("Operation")
            //    };
            //}

            //RoleManager<Role> roleManager = HttpContext.RequestServices.GetService<RoleManager<Role>>();
            Func<EntityRole, bool> updateFunc = FilterService.GetDataFilterExpression<EntityRole>(null, DataAuthOperation.Update).Compile();
            Func<EntityRole, bool> deleteFunc = FilterService.GetDataFilterExpression<EntityRole>(null, DataAuthOperation.Delete).Compile();
            //var page = DataAuthManager.EntityRoles.ToPage(predicate,
            //    request.PageCondition,
            //    m => new
            //    {
            //        D = m,
            //        RoleName = roleManager.Roles.First(n => n.Id == m.RoleId).Name,
            //        EntityName = m.EntityInfo.Name,
            //        EntityType = m.EntityInfo.TypeName,
            //    }).ToPageResult(data => data.Select(m => new EntityRoleOutputDto(m.D)
            //    {
            //        RoleName = m.RoleName,
            //        EntityName = m.EntityName,
            //        EntityType = m.EntityType,
            //        Updatable = updateFunc(m.D),
            //        Deletable = deleteFunc(m.D)
            //    }).ToArray());

            PageResult<EntityRoleOutputDto> page;
            using (var scope = ServiceProvider.CreateScope())
            {
                var roleRepository = scope.ServiceProvider.GetService<IRepository<Role, long>>();
                var entityInfoRepository = scope.ServiceProvider.GetService<IRepository<EntityInfo, long>>();

                page = CacheService.ToPageCache(DataAuthManager.EntityRoles, predicate, request.PageCondition, m => new
                {
                    D = m,
                    RoleName = GetRole(roleRepository, m.RoleId).Name,
                    EntityName = GetEntityInfo(entityInfoRepository, m.EntityId).Name,
                    EntityType = GetEntityInfo(entityInfoRepository, m.EntityId).TypeName,
                }, function).ToPageResult(data => data.Select(m => new EntityRoleOutputDto(m.D)
                {
                    RoleName = m.RoleName,
                    EntityName = m.EntityName,
                    EntityType = m.EntityType,
                    Updatable = updateFunc(m.D),
                    Deletable = deleteFunc(m.D)
                }).ToArray());
            }

            return page.ToPageData();
        }
        #endregion

        #region "新增角色数据权限"
        /// <summary>
        /// 新增角色数据权限
        /// </summary>
        /// <param name="dtos">角色数据权限信息</param>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [DependOnFunction(nameof(Read))]
        [DependOnFunction("ReadNode", Controller = "Role")]
        [DependOnFunction(nameof(EntityInfoController.ReadNode), Controller = nameof(EntityInfoController))]
        [UnitOfWork]
        [Description("新增")]
        public virtual async Task<AjaxResult> Create(params EntityRoleInputDto[] dtos)
        {
            Check.NotNull(dtos, nameof(dtos));

            OperationResult result = await DataAuthManager.CreateEntityRoles(dtos);
            return result.ToAjaxResult(true);
        }
        #endregion
        #region "更新角色数据权限"
        /// <summary>
        /// 更新角色数据权限
        /// </summary>
        /// <param name="dtos">角色数据权限信息</param>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [DependOnFunction(nameof(Read))]
        [DependOnFunction("ReadNode", Controller = "Role")]
        [DependOnFunction(nameof(EntityInfoController.ReadNode), Controller = nameof(EntityInfoController))]
        [UnitOfWork]
        [Description("更新")]
        public virtual async Task<AjaxResult> Update(params EntityRoleInputDto[] dtos)
        {
            Check.NotNull(dtos, nameof(dtos));
            OperationResult result = await DataAuthManager.UpdateEntityRoles(dtos);
            return result.ToAjaxResult(true);
        }
        #endregion
        #region "删除角色数据权限"
        /// <summary>
        /// 删除角色数据权限
        /// </summary>
        /// <param name="ids">用户数据权限编号</param>
        /// <returns>JSON操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [DependOnFunction(nameof(Read))]
        [UnitOfWork]
        [Description("删除")]
        public virtual async Task<AjaxResult> Delete(params long[] ids)
        {
            Check.NotNull(ids, nameof(ids));

            OperationResult result = await DataAuthManager.DeleteEntityRoles(ids);
            return result.ToAjaxResult();
        }
        #endregion

        #endregion

        #region "受保护的方法"
        #region "获取角色信息"
        /// <summary>
        /// 获取角色信息
        /// </summary>
        /// <param name="roleRepository">角色仓储模型</param>
        /// <param name="roleId">角色编号</param>
        /// <returns></returns>
        [NonAction]
        [NonFunction]
        protected static Role GetRole(IRepository<Role, long> roleRepository, long? roleId)
        {
            if (roleId == null)
            {
                return new Role();
            }
            var role = roleRepository.ToCacheFirst(o => o.Id == roleId, false, 10, false);
            return role ?? new Role();
        }
        #endregion
        #region "获取实体信息"
        /// <summary>
        /// 获取实体信息
        /// </summary>
        /// <param name="entityInfoRepository">实体信息仓储模型</param>
        /// <param name="entityId">数据编号</param>
        /// <returns></returns>
        [NonAction]
        [NonFunction]
        protected static EntityInfo GetEntityInfo(IRepository<EntityInfo, long> entityInfoRepository, long? entityId)
        {
            if (entityId == null)
            {
                return new EntityInfo();
            }
            var entityInfo = entityInfoRepository.ToCacheFirst(o => o.Id == entityId, false, 10, false);
            return entityInfo ?? new EntityInfo();
        }
        #endregion

        #endregion

    }
    #endregion

}
